import { useCallback, useMemo, useState } from 'react'
import { importAllFavorData, importOneId } from '@/api/batchQuery.ts'
import { initPageType, message, usePageChange } from '@hs-admin/utils'
import { favorDataList } from '@/api/favor.ts'
import { Button, Table } from 'antd'

const initPage: initPageType = {
  current: 1,
  total: 0,
  pageSize: 10
}
export const useAddByFavor = (theId: string, tableId: string, columns: Array<any>, resetCall: () => void) => {
  const [data, setData] = useState([])

  const getFields = useCallback(
    async (page: number, pageSize: number) => {
      const res = await favorDataList(tableId, {
        page,
        page_size: pageSize
      })
      setData(res.items)
      return res.total
    },
    [tableId]
  )

  const { resetPageAndTriggerRequest, pagination } = usePageChange(initPage, getFields)

  return useMemo(
    () => ({
      children: (
        <div className="flex gap-4 flex-col">
          <div>
            <Button
              disabled={!data?.length}
              type="link"
              onClick={() => {
                importAllFavorData(theId).then(() => {
                  message.success('添加成功')
                })
              }}>
              全部添加
            </Button>
          </div>
          <Table
            pagination={pagination}
            columns={[
              {
                title: '',
                key: 'doChoose',
                width: 70,
                fixed: 'left',
                render: (_, row) => (
                  <Button
                    type="link"
                    onClick={() => {
                      importOneId(theId, {
                        data_id: row.id
                      }).then(() => {
                        message.success('添加成功')
                      })
                    }}>
                    添加
                  </Button>
                )
              },
              ...columns
            ]}
            dataSource={data}
          />
        </div>
      ),
      onOk: () => {
        console.log('确认')
      },
      onCancel: () => {
        console.log('取消')
        resetCall()
      },
      title: '导入收藏数据',
      onOpen: () => {
        setData([])
        resetPageAndTriggerRequest()
      }
    }),
    [columns, data, pagination, resetCall, resetPageAndTriggerRequest, theId]
  )
}
